//
//  HomeViewController.swift
//  News
//
//  Created by qiupeng on 2017/6/3.
//  Copyright © 2017年 Speedy. All rights reserved.
//

import UIKit

private let kHomeCellID = "kHomeCellID"

class HomeViewController: UITableViewController {

    fileprivate lazy var newsModels : [NewsModel] = [NewsModel]()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // 1.设置导航栏
        setupNavigationBar()
        
        // 2.设置Tableview
        setupTableView()

        // 2.加载数据
        loadData()
    }

 
    // MARK: - Table view data source
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return self.newsModels.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        // 1.获取Cell
        let cell = tableView.dequeueReusableCell(withIdentifier: kHomeCellID, for: indexPath) as! NewsViewCell
        
        // 2.给Cell设置数据
        cell.newsModel = newsModels[indexPath.row]

        return cell
    }
}

// MARK:- 设置UI界面
extension HomeViewController{
    
    // 1.设置导航栏
    fileprivate func setupNavigationBar(){
        
        navigationController?.navigationBar.setBackgroundImage(UIImage(named: "reader_navigation_background"), for: .default)
        navigationItem.titleView = UIImageView(image: UIImage(named: "navigation_logo"))
        navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: ""), style: .plain, target: self, action: #selector(searchItemClick))
    }
}

// MARK:- 事件监听函数
extension HomeViewController {
    // @objc --> 为了保留OC的特性
    @objc fileprivate func searchItemClick() {
        print("-------")
    }
}


// MARK:- 网络数据的请求
extension HomeViewController {

    fileprivate func loadData(){
        
        
        HttpTools.requestData(URLString: "http://c.m.163.com/nc/article/list/T1348649079062/0-20.html", type: .get) { (result : Any) in
            
            guard let resultDict = result as? [String : Any] else {return}
            
            guard let dataArray = resultDict["T1348649079062"] as? [[String : Any]] else{ return  }
            
            for dict in dataArray{
                self.newsModels.append(NewsModel(dict:dict))
            }
            
            self.tableView.reloadData()
        }
        
    }

}

// MARK:- 设置TableView
extension HomeViewController{
    
    fileprivate func setupTableView(){
       
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: kHomeCellID)
        tableView.rowHeight = 90
        tableView.register(UINib(nibName: "NewsViewCell", bundle: nil), forCellReuseIdentifier: kHomeCellID)
    }

}










